package com.jrauto.CarAppBackend.mapper;

/**
 * @author : huiMing
 * Date : 2025年09月12日 11:17
 * @version V1.0
 */

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jrauto.CarAppBackend.entity.UserOnlineLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户在线日志Mapper接口
 */
@Mapper
public interface UserOnlineLogMapper extends BaseMapper<UserOnlineLog> {

    /**
     * 更新用户下线时间
     */
    @Update("UPDATE user_online_log SET offline_time = #{offlineTime} " +
            "WHERE user_id = #{userId} AND offline_time IS NULL " +
            "ORDER BY online_time DESC LIMIT 1")
    int updateOfflineTime(@Param("userId") Integer userId, @Param("offlineTime") LocalDateTime offlineTime);

    /**
     * 获取用户在线历史记录
     */
    @Select("SELECT * FROM user_online_log WHERE user_id = #{userId} " +
            "ORDER BY online_time DESC LIMIT #{limit}")
    List<UserOnlineLog> selectUserOnlineHistory(@Param("userId") Integer userId, @Param("limit") int limit);

    /**
     * 获取指定时间段内的在线统计
     */
    @Select("SELECT DATE(online_time) as date, COUNT(*) as count " +
            "FROM user_online_log " +
            "WHERE online_time BETWEEN #{startTime} AND #{endTime} " +
            "GROUP BY DATE(online_time) " +
            "ORDER BY date DESC")
    List<Object> getOnlineStatistics(@Param("startTime") LocalDateTime startTime,
                                     @Param("endTime") LocalDateTime endTime);

    /**
     * 清理过期的在线日志（保留最近30天）
     */
    @Update("DELETE FROM user_online_log WHERE created_at < #{expireTime}")
    int cleanExpiredLogs(@Param("expireTime") LocalDateTime expireTime);
}
